package auth

import (
	"GraduationProject/public/db"
	"GraduationProject/public/models"
	"GraduationProject/webserver/controllers/util"
	"GraduationProject/webserver/status"
	"fmt"
	"github.com/gin-gonic/contrib/sessions"
	"github.com/gin-gonic/gin"
	"net/http"
)

type User struct {
	Username string
	Password string
}

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	//fmt.Println("username", username)
	//fmt.Println("password", password)

	var user models.User
	if err := db.DB.Where("`username` = ? and `password` = ?", username, util.Sha256(password)).
		First(&user).Error; err != nil {
		util.FailedResponse(c, status.UsernameOrPasswordError, "用户名或密码错误")
		return
	}

	if user.Status == models.UserStatusRegister {
		util.FailedResponse(c, 10001, "未通过注册申请")
		return
	}

	if user.Status == models.UserStatusBand {
		util.FailedResponse(c, 10002, "用户已被禁用")
		return
	}

	// 管理员登陆
	if user.Authorization == models.UserAuthAdministrator {
		session := sessions.Default(c)
		session.Set("admin", user)
		if err := session.Save(); err != nil {
			c.JSON(http.StatusOK, gin.H{
				"status":  status.LoginError,
				"message": "登录错误",
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"status":  status.Normal,
			"message": "success",
		})
		return
	}

	if !(user.Authorization == models.UserAuthNormal ||
		user.Authorization == models.UserAuthMember) {
		c.JSON(http.StatusOK, gin.H{
			"status":  status.AuthorizationError,
			"message": "用户权限错误",
		})
		return
	}

	session := sessions.Default(c)
	session.Set("user", user)
	if err := session.Save(); err != nil {
		fmt.Println("session save error:", err)
		c.JSON(http.StatusOK, gin.H{
			"status":  status.LoginError,
			"message": "登录错误",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status":  status.Normal,
		"message": "success",
	})
	return
}
